package com.qf.controller;

import com.qf.entity.City;
import com.qf.entity.Hotal;
import com.qf.feign.CityFeign;
import com.qf.feign.HotalFeign;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/back")
public class BackHotalController {

    @Autowired
    private CityFeign cityFeign;

    @Autowired
    private HotalFeign hotalFeign;

    /**
     * 跳转到酒店添加页面
     * @return
     */
    @RequestMapping("/toHotalAdd")
    public String toHotalAdd(Model model){
        List<City> cities = cityFeign.queryCityList();
        model.addAttribute("citys", cities);
        return "hotaladd";
    }

    /**
     * 添加酒店   文件后缀没什么用  西游记.mp4
     * @return
     */
    @RequestMapping("/hotaladd")
    public String hotalAdd(MultipartFile file, Hotal hotal) throws IOException {

        //处理图片上传的问题
        //上传的文件名
        String name = UUID.randomUUID().toString();

        //获得当前服务器的classpath路径
        String uploadPath = BackHotalController.class.getResource("/").getPath() + "static/image/" + name;
        System.out.println("上传路径：" + uploadPath);

        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(uploadPath)
        ) {
            IOUtils.copy(in, out);
        } catch (IOException e) {
            throw e;
        }

        //将上传的图片设置到酒店对象中
        hotal.setHotalImage("http://localhost:9090/image/" + name);

        //调用酒店服务保存酒店信息
        hotalFeign.insertHotal(hotal);
        return "succ";
    }

    /**
     * 酒店列表
     * @return
     */
    @RequestMapping("/hotalList")
    public String backHotalList(Model model){

        List<Hotal> hotals = hotalFeign.queryAll();
        model.addAttribute(hotals);
        return "hotallist";
    }
}
